import { Component } from 'react';

import {TabBar,ActionSheet,Datetime,Toast,Popup,CalendarField, Group, Boxs, Tab, SearchBar, Grid, Slide, Button, ScrollList, Avatar, Dialog, Badge} from 'saltui';
const { HBox, Box } = Boxs;
const {
  IconButton,
  ButtonGroup,
} = Button;
import BottomTab from '../../../tab';

import Results from './result';
import './PageHome.less';



import {URLS,nodataIcon} from '../../../../app/variables';

import DB from '../../../../app/db';


let tabPage = '0';
let ActionSheetButton;

const Item  =  React.createClass({
  action:function(){
    let t = this;
    let options = ['查看'];
    if(this.props.status == 1){
      options.push('回退');
    }
    let id = this.props.id;
    let anUserId = this.props.createdBy;
    ActionSheetButton = ActionSheet.show({
        options: options,
        destructiveButtonIndex: 1,
        maskClosable: true,
      }, (index) => {
      if(index == 0){
        location.hash='questionnaire/ques_info/'+this.props.quesId+"/1/false/1/"+this.props.createdBy;
      }
      if(index == 1){//回退
        Dialog.confirm({
          title: '提示',
          locale: 'zh_CN',
          content: '确定回退该数据吗？',
          onConfirm() {
            DB.QuesModuleAPI.quesBack({
              id:id,
              anUserId:anUserId
            }).then((result)=>{
              if(result.type == 'success'){
                Toast.show({
                  type: 'success',
                  content: result.message,
                });
              }else{
                Toast.show({
                  type: 'error',
                  content: result.message,
                });
              }
              t.props.refresh();
            }).catch()
          },
          onCancel() {},
        });
      }
    })
  },

  render:function() {
    //type处理
    function formatType(type){
      switch (type){
        case '1':return '已提交';
        case '2':return '草稿';
        case '3':return '已回退';
        case 1:return '已提交';
        case 2:return '草稿';
        case 3:return '已回退';
      }
    }
    return <div onClick={this.action}>
      <Box className="t-BCf t-ML16 t-MR16 t-MT10 t-P12 t-PR0 t-R4">
        <HBox vAlign="center">
          <HBox flex={1} vAlign="center" className="t-LH1_4 t-PR10 t-FS16">
            <Box className="t-MAXW-78 t-omit">{this.props.userName}</Box>
            <Box className="t-FCddfontblue-10 t-ML4 t-MR4 t-FS12">|</Box>
            <Box className="t-FCddfontblue-40 t-FS14 t-omit" flex={1}>{this.props.orgUnitName}</Box>
          </HBox>
          <Box className={this.props.status==1?"t-FAC t-RL12 t-BCgreyblue-20 t-FCf t-H22 t-LH22 t-FS12 t-W56":"t-FAC t-RL12  t-BCcyan t-FCf t-H22 t-LH22 t-FS12 t-W56"}>{formatType(this.props.status)}</Box>
        </HBox>
        <HBox vAlign="center" className="t-MT8 t-FCddfontblue-40">
          <Box flex={1}>{this.props.createdDate.substring(0,10)}</Box>
          <Box><b className="iconfont icon-more t-FS18 t-PR16"></b></Box>
        </HBox>
      </Box>

    </div>;
  }
});


let indexTab = '0';
export default class PageHome extends Component {

 constructor(props) {
    super(props);
    let t = this;
    let userId = document.getElementById("userHiddenId").value;
    let winHeight ;
    let quesType = this.props.params.type;
    winHeight = getScrollHigh(1,1,0);
    this.state = {
      id:this.props.params.id,

      userId:userId,
      ableClick:true,
      activeIndex: 0,
      activeTabIndex:tabPage,
      winHeight:winHeight,
      search1:'',
      //搜索
      visible1: false,

      //答卷状态   只展示两种
      anStatusArr:[{'value':'1','text':'已提交'},{'value':'3','text':'已退回'}],

      // //问卷类型
      // typeArr:[{'value':'questionnaireVote','text':'投票'},{'value':'questionnaireSurvey','text':'调查'}],
      // //问卷状态
      // publishArr:[{'value':'1','text':'已发布'},{'value':'0','text':'未发布'}],


      status:"",
      //选择的问卷类型
      // type:"",
      //选择的问卷状态
      // publish:"",

      //筛选条件展示位
      anStatusArrow:false,
      //筛选条件展示位
      // quesTypeArrow : false,
      // quesPublishArrow : false,

      //筛选  问卷时间
      // time:null,
      startDate:null,
      endDate:null,
      quesType:quesType

    };
    if(quesType == "questionnaireExam"){
      setTitle('正确率统计'); 
    }else
    setTitle('统计结果'); 
  }

  //时间格式化   YYYY-MM-DD
  formatterDate(time){
    var date = new Date(time);
    var Y = date.getFullYear() + '-';
    var M = (date.getMonth() + 1 < 10 ? '0' + (date.getMonth() + 1) : date.getMonth() + 1) + '-';
    var D = date.getDate() < 10 ? "0" + (date.getDate()) : date.getDate();
    return Y+M+D;
  }

  //组件销毁执行
  componentWillUnmount(){
   if(ActionSheetButton){
     ActionSheetButton.close();
   }
  }

  //分页列表请求前
  beforeFetch1(data,form){
    let search = form.value;
    if(search == undefined){
      data.search = this.state.search;
    }else{
      data.search = form.value;
    }
    // let rows = data.pageSize;
    // data.rows = rows;

    if(this.state.startDate != null && this.state.startDate != ''){
      data.startDate = this.formatterDate(this.state.startDate);
    }
    if(this.state.endDate != null && this.state.endDate != ''){
      data.endDate = this.formatterDate(this.state.endDate);

    }
    // if(this.state.type != ''){
    //   data.quesType = this.state.type;
    // }
    if(this.state.status != ''){
      data.status = this.state.status;
    }
    data.quesId = this.state.id;
    return data;
  }


  //初始化按钮
  initButton(){
    //设置帮助
    //  dd.biz.navigation.setIcon({
    //     showIcon : true,//是否显示icon
    //     iconIndex : 2,//显示的iconIndex,如上图
    //     onSuccess : function(result) {
    //         /*结构
    //         {
    //         }*/
    //         //点击icon之后将会回调这个函数
    //         location.hash='document/help_index';
    //     },
    //     onFail : function(err) {
    //     //jsapi调用失败将会回调此函数
    //     }
    // });

    }

    /*跳到帮助*/
  skipHelp(path){
    let t = this;
    var userId = this.state.userId;
    dd.util.domainStorage.setItem({
     name:'document_'+userId , // 存储信息的key值
     value:'isLogin', // 存储信息的Value值
     onSuccess : function(info) {
          t.setState({
              isMask:false
             });
          location.hash=path;
     },
     onFail : function(err) {
     }
    });
    
  }
//刷新列表
  refresh(){
    let t = this;
    let value = t.state.search1;
    t.refs.reportComment_ref1.fetchData({value:value});
  }
  //改变筛选展示状态
  changeArrow(field){
    let t = this;
    let status = t.state[field];
    t.setState({
      [field]:!status
    })
  }


  //修改标题
  changeTitle(title){
    dd.biz.navigation.setTitle({
      title : title,//控制标题文本，空字符串表示显示默认文本
      onSuccess : function(result) {},
      onFail : function(err) {}
    });
  }

  //日期选择确认
  onOk(value,key){
    let t = this;
    if(key == "startDate" && t.state.endDate != null && t.state.endDate != ''){
      if(t.formatterDate(t.state.endDate) < t.formatterDate(value.value)){
        Toast.show({
          type: 'error',
          content: '开始日期不能大于结束日期'
        });
        return;
      }
    }
    if(key == "endDate" && t.state.startDate != null && t.state.startDate != ''){
      if(t.formatterDate(t.state.startDate) > t.formatterDate(value.value)){
        Toast.show({
          type: 'error',
          content: '结束日期不能小于开始日期'
        });
        return;
      }
    }
    t.setState({
      [key]:t.formatterDate(value.value)
    });
  }

  showSlot(id) {
    this[id].show();
  }

  changeTab(data){
    let index = parseInt(data.activeKey);
    indexTab = index + "";
  }

  render() {
    const t = this;
    let popHei=window.screen.height-60;
    const props = {
      locale: 'zh_CN',
      instantSearch: false,
      placeholder:'请输入答卷人员名称',
      hasHistory: true,
      searchDelay: 450,
      onEnter: (value) => { console.log(value); },
      onExit: () => { 
         t.setState({
          search1 :''
        },()=>{
           t.refs.reportComment_ref1.fetchData({
            value: ''
          });
        });

       },
      onChange: (value) => {
       console.log('onChange');
      },
      onSearch: (value) =>{
        t.setState({
          search1 :value
        },()=>{
           t.refs.reportComment_ref1.fetchData({
            value: value
          });
        });
       

      }
    };
    let winHeightStyle = {height: this.state.winHeight};
    let winHeights = getScrollHigh(1,0,0);
    let s = {height:winHeights};
    const datetimeProps = {
      locale: 'zh-cn',
    };
    return (
      <div  style={s}>
          <Results quesId={t.state.id}/>
      </div>
      );
    }
}


